package com.qingsong.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.qingsong.constant.ML;
import com.qingsong.dto.SeckillDetailInsertDTO;
import com.qingsong.dto.SeckillDetailPageDTO;
import com.qingsong.dto.SeckillDetailUpdateDTO;
import com.qingsong.entity.Course;
import com.qingsong.entity.SeckillDetail;
import com.qingsong.exception.ServiceException;
import com.qingsong.feign.CourseFeign;
import com.qingsong.mapper.SeckillDetailMapper;
import com.qingsong.service.SeckillDetailService;
import com.qingsong.vo.SeckillDetailSimpleListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

import static com.qingsong.entity.table.SeckillDetailTableDef.SECKILL_DETAIL;
import static com.qingsong.entity.table.SeasonTableDef.SEASON;
import static com.qingsong.entity.table.SeckillTableDef.SECKILL;

/**
 * 秒杀明细表 服务层实现。
 *
 * @author qingsong
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "seckill")
public class SeckillDetailServiceImpl extends ServiceImpl<SeckillDetailMapper, SeckillDetail>  implements SeckillDetailService{

    @Autowired
    private CourseFeign courseFeign;

    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(SeckillDetailInsertDTO dto) {
        // 组装 entity 实体类
        SeckillDetail seckillDetail = BeanUtil.copyProperties(dto, SeckillDetail.class);
        Course course = courseFeign.select(dto.getFkCourseId()).getData();
        //秒杀ID和课程ID的组合查重
        if(QueryChain.of(mapper)
                .where(SECKILL_DETAIL.FK_SECKILL_ID.eq(dto.getFkSeckillId()))
                .and(SECKILL_DETAIL.FK_COURSE_ID.eq(dto.getFkCourseId()))
                .exists()){
            throw new ServiceException("秒杀明细已存在") ;
        }
        seckillDetail.setCourseTitle(course.getTitle());
        seckillDetail.setCourseCover(course.getCover());
        seckillDetail.setCoursePrice(course.getPrice());
        seckillDetail.setSkPrice(seckillDetail.getSkPrice());
        seckillDetail.setSkCount(seckillDetail.getSkCount());
        seckillDetail.setCreated(LocalDateTime.now());
        seckillDetail.setUpdated(LocalDateTime.now());
        return mapper.insert(seckillDetail) > 0;
    }

    @Cacheable(key = "'detail:' + #p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public SeckillDetail select(Long id) {
        RelationManager.addQueryRelations("course", "seckill");
        return mapper.selectOneWithRelationsById(id);
    }

    @Override
    @Cacheable(key = "'detail:' + #root.methodName", unless = "#result == null")
    public List<SeckillDetailSimpleListVO> simpleList() {
        return QueryChain.of(mapper)
                .orderBy(SECKILL_DETAIL.ID.desc())
                .withRelations()
                .listAs(SeckillDetailSimpleListVO.class);
    }

    @Cacheable(key = "'detail:' + #root.methodName + ':' + #p0.toString()", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Page<SeckillDetail> page(SeckillDetailPageDTO dto) {
        RelationManager.addQueryRelations("course", "seckill");
        QueryChain<SeckillDetail> queryChain = QueryChain.of(mapper)
                .orderBy(SECKILL_DETAIL.ID.desc());
        // seckillId 条件
        Long seckillId = dto.getSeckillId();
        if (ObjectUtil.isNotNull(seckillId)) {
            queryChain.where(SECKILL_DETAIL.FK_SECKILL_ID.like(seckillId));
        }
        // CourseTitle 条件
        String CourseTitle = dto.getCourseTitle();
        if (ObjectUtil.isNotNull(CourseTitle)) {
            queryChain.where(SECKILL_DETAIL.COURSE_TITLE.like(CourseTitle));
        }
        return queryChain.withRelations()
                .page(new Page<>(dto.getPageNum(), dto.getPageSize()));
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(SeckillDetailUpdateDTO dto) {
        // 组装 entity 实体类
        SeckillDetail seckillDetail = BeanUtil.copyProperties(dto, SeckillDetail.class);
        Course course = courseFeign.select(dto.getFkCourseId()).getData();
        seckillDetail.setCourseTitle(course.getTitle());
        seckillDetail.setCourseCover(course.getCover());
        seckillDetail.setCoursePrice(course.getPrice());
        seckillDetail.setUpdated(LocalDateTime.now());
        return UpdateChain.of(seckillDetail)
                .where(SECKILL_DETAIL.ID.eq(seckillDetail.getId()))
                .update();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {
        return mapper.deleteById(id) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {
        return mapper.deleteBatchByIds(ids) > 0;
    }

}
